package com.jyu.service.impl;

import com.jyu.domain.LoginUser;
import com.jyu.domain.ResponseResult;
import com.jyu.domain.User;
import com.jyu.service.LoginService;
import com.jyu.util.JwtUtil;
import com.jyu.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        //模拟SpringSecurity框架中UsernamePasswordAuthenticationFilter的登录过程
        //由于在SecurityConfig的配置类重写了configure方法，就不会调用父类方法将UsernamePasswordAuthenticationFilter引入过滤器链中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        //调用ProviderManager的authenticate进行认证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //由Security框架内部的PasswordEncoder比较UserDetail和一开始封装Authentication的账号密码是否正确
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("认证失败请重新登录，用户名或密码错误");
        }
        //使用userId生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //将登陆的用户存入redis，并设置用户的过期时间默认为1分钟
        redisCache.setCacheObject("login:"+userId,loginUser,60, TimeUnit.SECONDS);
        //将token以键值对结构返回返回
        HashMap<String,String> map=new HashMap<>();
        map.put("token",jwt);
        return new ResponseResult(200,map);
    }

    @Override
    public ResponseResult logout() {
        //能访问到该接口，说明token解析成功，用户已经成功登录
        //从SecurityContextHolder获取在JWT过滤器存入的用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser= (LoginUser) authentication.getPrincipal();
        //拿到用户id，删除redis中的用户信息，当用户下一次访问接口时，首先会经过JWT过滤器
        //即使携带相同的token，解析出用户id，去redis中拿用户信息会拿不到，说明用户还未登录
        Long userId = loginUser.getUser().getId();
        redisCache.deleteObject("login:"+userId);
        return new ResponseResult(200,"退出成功");
    }
}
